package git.soulbgm.controller;

import git.soulbgm.pojo.User;
import git.soulbgm.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 *
 * @author SoulBGM
 * @date 2021/04/12
 */
@RequestMapping("userRepository")
@RestController
public class UserRepositoryController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("findAll")
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @PostMapping("save")
    public User save(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping("findById")
    public User findById(Long id) {
        return userRepository.findById(id).get();
    }

    @GetMapping("findOne")
    public User findOne(User user) {
        Example<User> example = Example.of(user);
        return userRepository.findOne(example).get();
    }

    @DeleteMapping("removeById")
    public long removeById(Long id) {
        try {
            userRepository.deleteById(id);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @PutMapping("updateById")
    public User updateById(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping("find")
    public List<User> find(User user) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<User> example = Example.of(user, exampleMatcher);
        return userRepository.findAll(example, Sort.by("id"));
    }


}
